package com.xgp.company.创建型模式.第一种_单例模式.静态内部类实现;


import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SingletonDemo04 {
    private SingletonDemo04() {

        //防治被反射
        synchronized (SingletonDemo04.class) {
            if(InnerClass.instance != null) {
                throw new RuntimeException("不要试图用反射破坏单例");
            }
        }
    }

    private static class InnerClass {
        private static final SingletonDemo04 instance = new SingletonDemo04();
    }

    public static SingletonDemo04 getInstance() {
        return InnerClass.instance;
    }
}

class SingletonDemo04Test {

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        SingletonDemo04 instance1 = SingletonDemo04.getInstance();

        //反射破坏单例
        Constructor<SingletonDemo04> declaredConstructor = (SingletonDemo04.class).getDeclaredConstructor(null);

        declaredConstructor.setAccessible(true);

        SingletonDemo04 instance1 = declaredConstructor.newInstance();
//        SingletonDemo04 instance2 = declaredConstructor.newInstance();

//        System.out.println(instance1 == instance2);

        System.out.println(instance1.hashCode());
//        System.out.println(instance2.hashCode());
    }
}
